
var netUtil = require('/../../utils/netUtil.js');
var util = require('/../../utils/util.js');
var app = getApp();

Page({
  data:{
 		 
 		logisticsCompany : '',  //物流公司
 		logisticsCompanyArray : getApp().globalData.saveTeaLogisticsCompanyArray,
		logisticsCode : '',   //物流单号
		inItems : [],   //存茶记录项
		comboArray : getApp().globalData.comboArray ,
		typeAndGoodArray : [[] , []],       //用户显示 选择品种picker的属性
		respTypeAndGoodArray : null,
		 
		sendSmsCodeText : '发送验证码',
 		smsCodeBoxShow : false,
 		verifyCode : '',
 		phoneNum : '',
 		sendSmsInteval : null
		
  },
  onLoad:function(options){
  	var that = this;
  	
  	//app.getUserOpedId(that.getAllTypeAndGoods);
  	
  	//检查是否已经 注册
 		app.checkHasRegister('SAVETEA',function(phone) {
 			
 			that.setData({
 		  	phoneNum : phone
 			});
 			
 			app.getUserOpedId(that.getAllTypeAndGoods);
 		});
  },
  onReady:function(){
  
  },
  onShow:function(){
    
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
  },

  onUnload:function(){
    // 页面关闭

  },
  
  bindLogisticsCompanyChange : function(e) {
  	var value = e.detail.value;
  	var logisticsCompany = this.data.logisticsCompanyArray[value].logisticsCompany;
  	this.setData({
  		logisticsCompany : logisticsCompany
  	});
   },
  
	
	//查询所有类别和商品
	getAllTypeAndGoods : function() {
		var that = this;
		
		var params = {
  		method : 'wechat.wisen.goods.all.query',
  		openId : app.globalData.userInfo.openid
  	}
		
		netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
				
				onPre: function() {
					netUtil.showLoadingDialog(that);
				},
				
				onSuccess: function(resp) {
					console.log(resp);
					
					netUtil.hideLoadingDialog(that);
					
					if(resp.ret == app.globalData.respSuccessCode) {
										
						var data = resp.data;
						
						var typeArray = data[0];
						var goodsArray = data[1];
						
						that.data.typeAndGoodArray[0] = typeArray;
						that.data.typeAndGoodArray[1] = goodsArray[0];
						
						that.setData({
							typeAndGoodArray : that.data.typeAndGoodArray,
							respTypeAndGoodArray : data
						});
						
 					} else {
						if(resp.message != undefined && resp.message != null && resp.message != '') {
 							netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 						} else {
 							netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 						}
					}
					
				},
				
				onError: function(res) {
					console.log("fail");
					netUtil.hideLoadingDialog(that);
					netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
				}
				
			}).send();
		
	},
	
	//输入物流公司
	inputLogisticsCompany : function(e) {
		var logisticsCompany = e.detail.value;
		this.setData({
			logisticsCompany : logisticsCompany
		});
	},
	
	inputLogisticsCode : function(e) {
			var logisticsCode = e.detail.value;
			this.setData({
				logisticsCode: logisticsCode
			});
	},
	
	addSaveTeaItem : function() {
		var teaItem = {
			goodsId : '',
			goodsName : '',
			unitQuantity : 0.0,
			packageQuantity :0,
			combo : this.data.comboArray[0].comboKey,
			comboValue : this.data.comboArray[0].comboValue
		};
		this.data.inItems.push(teaItem);
		this.setData({
			inItems : this.data.inItems
		});
	},
	
	reduceSaveTeaItem : function(e) {
		var initemsindex = e.currentTarget.dataset.initemsindex;
		this.data.inItems.splice(initemsindex,1);
		this.setData({
			inItems : this.data.inItems
		})
	},
	
	//选择数量
	inputTeaCount : function(e) {
		var initemsindex = e.currentTarget.dataset.initemsindex;
		var packageQuantity = e.detail.value;
		
		this.data.inItems[initemsindex].packageQuantity = packageQuantity;
		
		this.setData({
			inItems : this.data.inItems
		});	
	},
	
	//选择套餐
	 chooseCombo: function(e) {
   	
   	var value = e.detail.value;  //选中的数组的下表
   	var initemsindex = e.currentTarget.dataset.initemsindex;
   	
   	this.data.inItems[initemsindex].combo = this.data.comboArray[value].comboKey;
   	this.data.inItems[initemsindex].comboValue = this.data.comboArray[value].comboValue;
   	
   	this.setData({
   		inItems : this.data.inItems
   	});
   	
  },
  
  //列值改变事件
  bindTypeAndGoodsColumnChange : function(e) {
  	var column = e.detail.column;
  	var value = e.detail.value;
  
  	//如果改变第一列
  	if(column == 0) {
  		this.data.typeAndGoodArray[1] = this.data.respTypeAndGoodArray[1][value];
  		this.setData({
  			typeAndGoodArray : this.data.typeAndGoodArray
  		});
  	}
  },
  
  //列值确定事件
  bindTypeAndGoodsChange :function(e) {
  	
  	var value = e.detail.value;
  	
  		//由于小程序的bug，第二列动态切换后，如果选择切换后默认的第一个，数据的第二个元素返回 null
  	for(var i=0;i<value.length;i++) {
  		var columnValue = value[i];
  		if(columnValue == null || columnValue == undefined) {
  			value[i] = 0;
  		}
  	}
  	
  	var arrayIndex = e.currentTarget.dataset.initemsindex;
  	var selectGoddIndex = value[1];
  	
  	//1.设置数据对应下标的值
  	var selectedGoodObj = this.data.typeAndGoodArray[1][selectGoddIndex];
  	this.data.inItems[arrayIndex].goodsId = selectedGoodObj.goodsId;
  	this.data.inItems[arrayIndex].goodsName = selectedGoodObj.goodsName;
  	
  	this.setData({
  		inItems : this.data.inItems
  	});
  	
  	//2.所有选项回复到最初始的状态
  	//this.bindTypeAndGoodsCancel();
  },
  
  //点击取消选择，所有选项回复最初始的状态
  bindTypeAndGoodsCancel : function(e) {
  	this.data.typeAndGoodArray[0] = this.data.respTypeAndGoodArray[0];
  	this.data.typeAndGoodArray[1] = this.data.respTypeAndGoodArray[1][0];
  	
  	this.setData({
  		typeAndGoodArray : this.data.typeAndGoodArray
  	});
  },
  
  doSubmitSaveTea : function(e) {
  	
  	var that = this;
  	
  	app.getUserOpedId(function() {
  		
			var inItems = [];
			
			//清除 值为 空的元素
			for(var i=0;i<that.data.inItems.length;i++) {
				var obj = that.data.inItems[i]
				if(obj.goodsId != null && obj.goodsId != '' && obj.packageQuantity != null && obj.packageQuantity != 0 && obj.combo != null && obj.combo != '') {
						inItems.push(obj);
					}
			}
			
			if(inItems.length <= 0) {
				netUtil.showAlertDialog("提示", '没有有效的记录', false, "确定", null, null);
				return;
			}
			
			var params = {
  			method : 'wechat.wisen.in.voucher.save',
  			openId : app.globalData.userInfo.openid,
  			data : {
  				logisticsCompany : that.data.logisticsCompany,
  				logisticsCode : that.data.logisticsCode,
  				inItems  :  inItems
  			}
  		};
  		
  		netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
				
				onPre: function() {
					netUtil.showLoadingDialog(that);
				},
				
				onSuccess: function(resp) {
					
					netUtil.hideLoadingDialog(that);
					
					if(resp.ret == app.globalData.respSuccessCode) {
								
							//存茶成功后，跳转到订单页	
							wx.reLaunch({
								url: '/pages/order/order?from=saveTea'
							});
						
 					} else {
						if(resp.message != undefined && resp.message != null && resp.message != '') {
 							netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 						} else {
 							netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 						}
					}
					
				},
				
				onError: function(res) {
					 console.log("fail");
					 netUtil.hideLoadingDialog(that);
					 netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
				}
				
			}).send();
  		
  		
  	});
  },
  
  submitSaveTea : function(e) {
  	
  	var that = this;
    var inItems = [];
    var flag=0;
    //清除 值为 空的元素
    for (var i = 0; i < that.data.inItems.length; i++) {
      var obj = that.data.inItems[i]
      if (obj.goodsId != null && obj.goodsId != '' && obj.packageQuantity != null && obj.packageQuantity != 0 && obj.combo != null && obj.combo != '') {
        inItems.push(obj);
      }
      if (obj.goodsId != null && obj.goodsId != '' && obj.goodsName.indexOf('2019')==-1) {
        flag=1;
      }
    }

    if (inItems.length <= 0) {
      netUtil.showAlertDialog("提示", '没有有效的记录', false, "确定", null, null);
      return;
    }else{
      if(flag=1){
        that.setData({
          isSaveOldTea: true,
        });
      }else{
      that.setData({
        smsCodeBoxShow: true,
      });
      }
    }

  	
  
  	
  	
/*  	app.getUserOpedId(function() {
  		
			var inItems = [];
			
			//清除 值为 空的元素
			for(var i=0;i<that.data.inItems.length;i++) {
				var obj = that.data.inItems[i]
				if(obj.goodsId != null && obj.goodsId != '' 
					&& obj.packageQuantity != null && obj.combo != null && obj.combo != '') {
						inItems.push(obj);
					}
			}
			
			if(inItems.length <= 0) {
				netUtil.showAlertDialog("提示", '没有有效的记录', false, "确定", null, null);
				return;
			}
			
			var params = {
  			method : 'wechat.wisen.in.voucher.save',
  			openId : app.globalData.userInfo.openid,
  			data : {
  				logisticsCompany : that.data.logisticsCompany,
  				logisticsCode : that.data.logisticsCode,
  				inItems  :  inItems
  			}
  		};
  		
  		netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
				
				onPre: function() {
					netUtil.showLoadingDialog(that);
				},
				
				onSuccess: function(resp) {
					
					netUtil.hideLoadingDialog(that);
					
					if(resp.ret == app.globalData.respSuccessCode) {
								
							//存茶成功后，跳转到订单页	
							wx.reLaunch({
								url: '/pages/order/order?from=saveTea'
							});
						
 					} else {
						if(resp.message != undefined && resp.message != null && resp.message != '') {
 							netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 						} else {
 							netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 						}
					}
					
				},
				
				onError: function(res) {
					 console.log("fail");
					 netUtil.hideLoadingDialog(that);
					 netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
				}
				
			}).send();
  		
  		
  	});*/
  },
  //确定继续存
  checkSave: function () {
    this.setData({
      isSaveOldTea: false,
      smsCodeBoxShow: true,
     
    })
  },
  //取消存
  hideSave: function () {
    this.setData({
      isSaveOldTea: false,
     
    })
  },
  //点击发送验证码触发的方法
  sendSms:function() {
  	
  	var that = this;
  	
  	//如果已经发送过验证码，一分钟倒计时还没完成，不做处理
  	if(that.data.sendSmsCodeText != '发送验证码') {
  			var secStr = '';

				if(that.data.sendSmsCodeText.length == 6) {
					secStr = that.data.sendSmsCodeText.substring(0, 2);
				} else {
					secStr = that.data.sendSmsCodeText.substring(0, 1);
				}

				var secInt = parseInt(secStr);
				var newSecInt = secInt - 1;

				if(newSecInt <= 0) {

					this.setData({
						sendSmsCodeText: '发送验证码'
					});

					clearInterval(that.data.sendSmsInteval);

					that.setData({
						sendSmsInteval: null
					});

				} else {
					that.setData({
						sendSmsCodeText: newSecInt + '秒后重发'
					});
				}
  		return;
  	}
  	
  	var phoneNum = this.data.phoneNum;
  	if(phoneNum != null && phoneNum.length == 11 && util.isPoneAvailable(phoneNum)) {
  		
  		app.getUserOpedId(function() {
  			
  			var params = {
  				method : 'wechat.wisen.commom.verify.generate',
  				openId : app.globalData.userInfo.openid,
  				data : {
  					phoneNum : that.data.phoneNum
  				}
  			};
  				
  			netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
				
				onPre: function() {
					netUtil.showLoadingDialog(that);
				},
				
				onSuccess: function(resp) {
					
					netUtil.hideLoadingDialog(that);
					
					if(resp.ret == app.globalData.respSuccessCode) {
								
						  	if('发送验证码' == that.data.sendSmsCodeText) {
						  		var text = '60秒后重发';
						  		that.setData({
						  			sendSmsCodeText: text
						  		});

						  		var sendSmsInteval = setInterval(that.sendSms, 1000);

						  		that.setData({
						  			sendSmsInteval: sendSmsInteval
						  		});

						  	} 
						
 						} else {
							if(resp.message != undefined && resp.message != null && resp.message != '') {
 								netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
 							} else {
 								netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
 							}
						}
					
					},
				
					onError: function(res) {
						 console.log("fail");
						 netUtil.hideLoadingDialog(that);
						 netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
					}
				
				}).send();
  				
  		});
  		
  	} else {
  		 netUtil.showAlertDialog("提示", '请输入正确手机号码', false, "确定", null, null);
  	}
  },
  
     //检查验证码是否正确
  checkSmsCode : function(e) {
  	
  	var that = this;
  	
  	var verifyCode = that.data.verifyCode;
  	
  	//发送请求检查验证码
  	if(verifyCode != null && verifyCode != '') {
  		app.getUserOpedId(function() {
  			var params = {
  				method : 'wechat.wisen.commom.verify.check',
  				openId : app.globalData.userInfo.openid,
  				data : {
  					phoneNum : that.data.phoneNum,
  					verifyCode : verifyCode
  				}
  			};
  			
  			netUtil.buildRequest(that,'/wisen/api/wechat/ret',params,{
  				onPre: function() {
						
					},
					
					onSuccess: function(resp) {
						
						//如果验证码正确，不做处理
						if(resp.ret == app.globalData.respSuccessCode) {
							
							that.hideSmsCodeBox();
							
							that.doSubmitSaveTea();
						
						} else {   //验证码错误，弹出提示框
							netUtil.showAlertDialog("提示",resp.message, false, "确定", null, null);
						}
					},
					
					onError: function(res) {
						 console.log("fail");
						 netUtil.hideLoadingDialog(that);
						 netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
					}
					
  			}).send();
  			
  		});
  	}
  },
  
  hideSmsCodeBox : function() {
		this.setData({
			smsCodeBoxShow : false,
			verifyCode : ''
		})
	},
	
	inputSmsCode: function(e) {

		var verifyCode = e.detail.value;
		this.setData({
			verifyCode : verifyCode
		});
	},
	
	
})